package com.dn.config;

import com.alibaba.fastjson.JSONObject;
import com.dn.MyStart;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * @program: ddns
 * @description: 获取本机IPv6地址
 * @author: DN
 * @create: 2021-04-03 16:24
 **/
public class IPv6Address {


    public static String getIp() {
        String result = null;
        try {
            result = postGeneralUrl("http://ipv6.lookup.test-ipv6.com/ip/","application/json","","UTF-8");
        } catch (Exception e) {
            System.out.println(LocalDateTime.now().format(MyStart.formatter)+" -> IPv6Address -> 错误,检查当前网络是否可用并且是否支持IPv6!");
            e.printStackTrace();
        }
        if (null == result || "".equals(result)){
            return "";
        }
        Map<String,Object> map = JSONObject.parseObject(result);

        if (null == map.get("ip")||"".equals(map.get("ip"))) return "";

        return (String) map.get("ip");

    }

    // String params,
    public static String postGeneralUrl(String generalUrl, String contentType,String params,  String encoding)
            throws Exception {
        URL url = new URL(generalUrl);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        if (!(null == params || "".equals(params))){
            out.write(params.getBytes(encoding));
        }

        out.flush();
        out.close();

        // 建立实际的连接
        connection.connect();
        // 获取所有响应头字段
        // Map<String, List<String>> headers = connection.getHeaderFields();
        // 遍历所有的响应头字段
        // for (String key : headers.keySet()) {
        //     System.err.println(key + "--->" + headers.get(key));
        // }
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in = null;
        in = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), encoding));
        String result = "";
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result += getLine;
        }
        in.close();
        // System.err.println("result:" + result);
        return result;
    }
}
